package com.frejoys.admin.controller;

import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.admin.AdminLoginDto;
import com.frejoys.common.enums.ESite;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.EncryptUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.common.LoginVo;
import com.frejoys.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangzhicheng
 * @version 1.0
 * @date 2024/4/19 14:39
 */
@Tag(name = "登陆管理", description = "后台用户登陆管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixAdmin)
@Authorization(Authority.Private)
public class AdminLoginController {

    private final UserService userService;

    private final RedissonClient redissonClient;

    /**
     * 后台用户登陆
     *
     * @param dto
     * @return
     */
    @Operation(summary = "后台用户登陆")
    @Authorization(Authority.Protected)
    @PostMapping("/login")
    Result<LoginVo> adminLogin(@RequestBody @Validated AdminLoginDto dto){

        // 解密
        dto.setPhone(EncryptUtil.adminAes.decryptStr(dto.getPhone()));
        dto.setPassword(EncryptUtil.adminAes.decryptStr(dto.getPassword()));

        LoginVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.loginLockCacheKey(dto.getPhone(), ESite.admin.getValue()));

        if (lock.tryLock()) {
            try {

                vo = userService.adminLogin(dto, ESite.admin.getValue(), RequestUtil.siteType());

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }

}
